#include "StudentManager.h"

StudentManager::StudentManager( QWidget* parent )
	: QSplitter( Qt::Vertical, parent )
	, mSelectedStudent( NULL )
{
	QWidget* managerWidget = new QWidget( this );
	addWidget( managerWidget );

	// Layout
	QVBoxLayout* layout = new QVBoxLayout();
	managerWidget->setLayout( layout );

	// Buttons
	QHBoxLayout* buttonLayout = new QHBoxLayout();
	layout->addItem( buttonLayout );

	QPushButton* addButton = new QPushButton( tr( "Add" ), managerWidget );
	connect( addButton, SIGNAL( pressed() ), this, SLOT( add() ) );
	buttonLayout->addWidget( addButton );

	QPushButton* removeButton = new QPushButton( tr( "Remove" ), managerWidget );
	connect( removeButton, SIGNAL( pressed() ), this, SLOT( remove() ) );
	buttonLayout->addWidget( removeButton );

	// Tree
	mTree = new QTreeWidget( managerWidget );
	mTree->setHeaderLabels( QStringList( tr( "id" ) ) << tr( "Name" ) );
	connect( mTree, SIGNAL( itemActivated( QTreeWidgetItem*, int ) ), this, SLOT( itemSelected( QTreeWidgetItem*, int ) ) );
	layout->addWidget( mTree );

	// Student Editor
	mStudentEditor = new StudentEditor( this );
	addWidget( mStudentEditor );
}

StudentManager::~StudentManager()
{
}

void
StudentManager::add()
{
	bool ok;
	int id = QInputDialog::getInt( this, tr( "Id" ), tr( "Student id:" ), 0, 0, 999999999, 1, &ok );
	if( ok )
	{
		if( mStudents.contains( id ) )
		{
			QMessageBox::warning( this, tr( "Add Student" ), tr( "A Student with that id already exists." ) );
		}
		else
		{
			QString name = QInputDialog::getText( this, tr( "Name" ), tr( "Student name:" ), QLineEdit::Normal, tr( "name" ), &ok );
			if( ok && !name.isEmpty() )
			{
				Student* student = new Student( id, name );
				mStudents[id] = student;

				mTree->insertTopLevelItem( 0, student );
			}
		}
	}

}

void
StudentManager::remove()
{
	if( QMessageBox::warning( this, tr( "Remove" ), tr( "All unsaved progress will be lost" ), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok ) == QMessageBox::Ok )
	{
	}
}

void
StudentManager::itemSelected( QTreeWidgetItem* item, int col )
{
	Student* student = static_cast< Student* >( item );
	mStudentEditor->editStudent( student );
}